import os
import threading
import pyperclip
from tkinter import messagebox, Toplevel, Label, Button, Text, Scrollbar, RIGHT, Y, BOTH, END
from tkinter.ttk import Progressbar

from minio_file_manager import download_word_file_from_minio, write_responses_to_word_file
from utils import center_window
from openai import OpenAI
from db import get_prompt_contents


def display_form_and_generate_doc(responses):
    """展示表格表单，并根据用户输入生成文档"""

    input_data = {"姓名": "", "手机": "", "工号": ""}  # 使用字典作为共享变量

    def generate_doc():
        """处理用户输入后生成文档"""
        input_data["姓名"] = name_entry.get().strip()
        input_data["手机"] = phone_entry.get().strip()
        input_data["工号"] = id_entry.get().strip()

        if any(value == "" for value in input_data.values()):
            messagebox.showerror("错误", "请完整填写所有信息")
            return

        form_window.destroy()

        try:
            download_path = "/Users/lvfushun/Downloads/patent.docx"
            download_word_file_from_minio(download_path)
            write_responses_to_word_file(word_file_path=download_path, responses=responses, save_path=download_path,
                                         extra_data=input_data)
            messagebox.showinfo("成功", "文档已生成并保存！")
        except Exception as e:
            messagebox.showerror("错误", f"生成文档失败：{str(e)}")

    # 创建表格输入窗口，并布局文本框
    # 剩下部分保持一致...

    # 创建表格输入窗口
    form_window = Toplevel()
    form_window.title("填写基础信息")

    # 创建表格布局
    Label(form_window, text="姓名").grid(row=0, column=0, padx=10, pady=10)
    name_entry = Text(form_window, height=1, width=30)
    name_entry.grid(row=0, column=1, padx=10, pady=10)

    Label(form_window, text="手机").grid(row=1, column=0, padx=10, pady=10)
    phone_entry = Text(form_window, height=1, width=30)
    phone_entry.grid(row=1, column=1, padx=10, pady=10)

    Label(form_window, text="工号").grid(row=2, column=0, padx=10, pady=10)
    id_entry = Text(form_window, height=1, width=30)
    id_entry.grid(row=2, column=1, padx=10, pady=10)

    # 添加确认按钮
    confirm_button = Button(form_window, text="生成文档", command=generate_doc)
    confirm_button.grid(row=3, columnspan=2, pady=10)

    # 居中表单窗口
    center_window(form_window, 400, 200)


def handle_responses(responses):
    """处理 responses 完成后的逻辑"""

    # 展示所有回答
    all_answers = "\n\n".join(f"{item['answer']}" for item in responses)
    messagebox.showinfo("请求完成", f"以下为所有问题的回答：\n\n{all_answers}")
    pyperclip.copy(all_answers)
    messagebox.showinfo("成功", "所有回答已复制到粘贴板")

    # 弹窗让用户选择是否生成文档
    if messagebox.askyesno("生成文档", "是否要生成文档？"):
        display_form_and_generate_doc(responses)


DATABASE_CONFIG = {
    "host": "10.0.25.150",
    "port": 8306,
    "user": "erdp_test",
    "password": "seres_2022_test",
    "database": "lfs"
}


def send_post_request_with_loading(full_code):
    def cancel_request():
        nonlocal is_canceled
        is_canceled = True
        loading_window.destroy()

    def process_requests():
        nonlocal is_canceled
        messages = [{"role": "system", "content": "You are a helpful assistant."}]
        responses = []

        try:
            # 从数据库获取 contents
            contents = get_prompt_contents(DATABASE_CONFIG)

            # 如果 contents 为空，提示并退出
            if not contents:
                messagebox.showerror("错误", "没有从数据库中获取到内容")
                return

            number_of_contents = len(contents)

            for index, content in enumerate(contents):
                if index == 0:
                    content += "\n" + full_code
                if is_canceled:
                    messagebox.showinfo("取消", "请求已取消")
                    break

                # 更新进度条，表示开始处理新的内容
                progress = int((index / number_of_contents) * 100)
                progress_bar['value'] = progress
                loading_window.update_idletasks()

                # 添加当前用户问题到对话上下文
                messages.append({"role": "user", "content": content})

                # 清理上一次的输出显示
                output_text.delete('1.0', END)

                # 发起流式请求
                completion = client.chat.completions.create(
                    model="qwen-plus",
                    messages=messages,
                    stream=True,
                    stream_options={"include_usage": True}
                )

                full_response = ""
                for chunk in completion:
                    if is_canceled:
                        break

                    # 检查流内容是否包含数据
                    if chunk.choices and chunk.choices[0].delta:
                        chunk_content = chunk.choices[0].delta.content
                        full_response += chunk_content

                        # 以线程安全方式更新 UI
                        output_text.insert(END, chunk_content)
                        output_text.see(END)
                        loading_window.update_idletasks()

                if is_canceled:
                    break

                # 更新上下文和存储完整结果
                messages.append({"role": "assistant", "content": full_response})
                responses.append({"question": content, "answer": full_response})

            # 在最后一步完成时设置进度为 100%
            progress_bar['value'] = 100
            loading_window.update_idletasks()

        except Exception as e:
            messagebox.showerror("请求失败", f"请求过程中出错: {str(e)}")
        finally:
            if not is_canceled:
                loading_window.destroy()
            if responses:
                handle_responses(responses)

    # 初始化加载窗口
    is_canceled = False
    loading_window = Toplevel()
    loading_window.title("加载中...")

    # 添加进度条
    progress_label = Label(loading_window, text="请求处理中，请稍候...")
    progress_label.pack(pady=10)

    progress_bar = Progressbar(loading_window, maximum=100)
    progress_bar.pack(pady=10, fill='x', padx=20)

    # 添加文本框和滚动条
    output_text = Text(loading_window, wrap="word", height=20)
    output_scrollbar = Scrollbar(loading_window, orient="vertical", command=output_text.yview)
    output_text.configure(yscrollcommand=output_scrollbar.set)
    output_text.pack(side="left", fill=BOTH, expand=True, padx=10, pady=10)
    output_scrollbar.pack(side="right", fill=Y)

    # 添加取消按钮
    cancel_button = Button(loading_window, text="取消", command=cancel_request)
    cancel_button.pack(pady=10)

    # 居中加载窗口
    center_window(loading_window, 600, 400)

    loading_window.protocol("WM_DELETE_WINDOW", cancel_request)

    # 定义 OpenAI 客户端
    client = OpenAI(
        api_key="sk-39187a37f0054c8eaeac657a2c73f8a0",
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
    )

    # 启动新线程处理请求
    threading.Thread(target=process_requests, daemon=True).start()
